// @flow
import React, { Component } from 'react'
import styles from './TaskToolBar.css'
import { Input, Row, Col, Button, Select } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const Option = Select.Option
import { connect } from 'react-redux'

type Props = {
  userId: string,
  tasks: Array<any>,
  getTasks: Function
}
type States = {
  modelName: Array<any>,
  owner: Array<any>,
  deviceType: Array<any>,
  customer: Array<any>,
  rowData: Array<any>,
  searchInfo: Object<any>
}
class TaskToolBar extends Component {
  props: Props
  state: States
  hasTasks: boolean
  searchInfo: Object
  getData: Function
  onPageChange: Function
  handleModelName: Function
  handleStatus: Function
  handleOwner: Function
  handleSearch: Function
  handleTaskName: Function
  handleDeviceType: Function
  constructor (props: Props) {
    super(props)
    this.searchInfo = {
      taskName: '',
      modelName: '',
      owner: '',
      customer: '',
      deviceType:''
    }
    this.state = {
      modelName: [],
      owner:[{ name: '全部', id: '0' }, { name: '手动', id: 'manual' }, { name: '自动', id: 'auto' }],
      customer: [{ id: 0, name: '全部' }],
      rowData: [],
      deviceType: [],
      searchInfo: {
        modelName: '模型名称',
        owner: '任务类型',
        customer: '客户',
        deviceType: '设备类型'
      }
    }
    this.hasTasks = false
    this.handleModelName = this.handleModelName.bind(this)
    this.handleStatus = this.handleStatus.bind(this)
    this.handleOwner = this.handleOwner.bind(this)
    this.handleSearch = this.handleSearch.bind(this)
    this.handleTaskName = this.handleTaskName.bind(this)
    this.handleDeviceType = this.handleDeviceType.bind(this)
  }
  componentDidMount () {
    this.getFillterDatas(`${__SERVICE_API__}device/customers?userId=${this.props.userId}&pageSize=200000`, 'customer')
  }
  componentWillReceiveProps (nextProps: any) {
    // if (this.hasTasks) return
    // this.hasTasks = true
    // let task = nextProps.tasks.map(item => {
    //   const modelNames = item.model
    //   const customers = item.customer
    //   const deviceTypes = item.deviceTypeJson
    //   return { customers, deviceTypes, modelNames }
    // })
    // let modelName = (Array.from(new Set(task.map(item => item.modelNames)))).filter(item => item)
    // let customer = (Array.from(new Set(task.map(item => item.customers)))).filter(item => item)
    // let deviceType = (Array.from(new Set(task.map(item => item.deviceTypes)))).filter(item => item)
    // modelName.unshift({ id: ' ', name: '全部' })
    // deviceType.unshift({ value: '0', label: '全部' })
    // customer.unshift({ key: ' ', label: '全部' })
    // this.setState({
    //   modelName, customer, deviceType
    // })
  }
  getFillterDatas (url: string, name: string) {
    universalFetch(url)
    .then(res => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      let data = this.state[name]
      data.push(...json.result)
      this.setState({ [name]: data })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }
  handleModelName (value: any) {
    this.searchInfo.modelName = value
  }
  handleOwner (value: any) {
    this.searchInfo.owner = value
  }
  handleStatus (value: any, e: any) {
    this.searchInfo.customer = value
  }
  handleDeviceType (value: any) {
    this.searchInfo.deviceType = value
  }
  handleSearch () {
    let { taskName, owner, customer, deviceType, modelName } = this.searchInfo
    if (deviceType === '0') {
      deviceType = ''
    }
    if (owner === '0') {
      owner = ''
    }
    let data = `?taskName=${taskName}&modelId=${modelName}` +
    `&taskType=${owner}&deviceType=${deviceType}&customer=${customer}`
    this.props.getTasks(data)
  }
  handleTaskName (e: any) {
    this.searchInfo.taskName = e.target.value
  }
  render () {
    const { modelName, owner, customer, deviceType } = this.state
    // 模型名称下拉列表,这一版暂时不用
    // const modelNameSelect = (
    //   <Col className={styles['ant-col-2']} span={2}>
    //     <div className='gutter-box'>
    //       <Select
    //         showSearch
    //         placeholder='模型名称'
    //         optionFilterProp='children'
    //         filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
    //         className={styles['selctBox']}
    //         onSelect={this.handleModelName}
    //      >
    //         {modelName.map((item, index) => {
    //           return <Option value={item.id} key={index} className={styles['optionBox']}>{item.name}</Option>
    //         })}
    //       </Select>
    //     </div>
    //   </Col>
    // )

    //  设备名称下拉列表,这一版暂时不用
    //  const deviceNameSlect  = (
    //  <Col className={styles['ant-col-2']} span={2}>
    //   <div className='gutter-box'>
    //     <Select
    //       showSearch
    //       placeholder='设备类型'
    //       optionFilterProp='children'
    //       filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
    //       className={styles['selctBox']}
    //       onSelect={this.handleDeviceType}
    //    >
    //       {deviceType.map((item, index) => {
    //         return <Option value={item.value} key={index} className={styles['optionBox']}>{item.label}</Option>
    //       })}
    //     </Select>
    //   </div>
    // </Col>)
    return (
      <div className={styles['searchBox']}>
        <Row gutter={24} justify='center'>
          <Col className={styles['ant-col-3']} span={3}>
            <div className='gutter-box'>
              <Input placeholder='搜索任务' onBlur={this.handleTaskName} ref='input'
                onPressEnter={this.handleSearch} />
            </div>
          </Col>
          <Col className={styles['ant-col-2']} span={2}>
            <div className='gutter-box'>
              <Select
                showSearch
                placeholder='任务类型'
                optionFilterProp='children'
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                className={styles['selctBox']}
                onSelect={this.handleOwner}
             >
                {owner.map((item, index) => {
                  return <Option value={item.id} key={index} className={styles['optionBox']}>{item.name}</Option>
                })}
              </Select>
            </div>
          </Col>
          <Col className={styles['ant-col-2']} span={2}>
            <div className='gutter-box'>
              <Select
                showSearch
                placeholder='客户'
                optionFilterProp='children'
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                className={styles['selctBox']}
                onSelect={this.handleStatus}
             >
                {customer.map((item, index) => {
                  return <Option value={item.id} key={index + item} title={item.name}
                    className={styles['optionBox']}>{item.name}</Option>
                })}
              </Select>
            </div>
          </Col>
          <Col className={styles['ant-col-2']} span={2} style={{ width: '100px' }}>
            <div className='gutter-box'>
              <Button icon='search' type='primary' onClick={this.handleSearch}>搜索</Button>
            </div>
          </Col>
        </Row>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {})(TaskToolBar)
